package cz.cvut.manatee.client;

import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.ui.TextBox;

public class IntegerTextBox extends TextBox {
	int defaultValue;
	
	public IntegerTextBox() {
		this(0);
	}
	
	public IntegerTextBox(int defaultValue) {
		super();
		this.defaultValue = defaultValue;
		this.setValue(""+this.defaultValue);
		
		this.addChangeHandler(new ChangeHandler() {
			public void onChange(ChangeEvent event) {
				IntegerTextBox.this.parseInt(true);
			}
		});
		
		this.addKeyPressHandler(new KeyPressHandler() {
			public void onKeyPress(KeyPressEvent event) {
				IntegerTextBox.this.parseInt(false);
			}
		});
		
		this.addKeyUpHandler(new KeyUpHandler() {
			public void onKeyUp(KeyUpEvent event) {
				IntegerTextBox.this.parseInt(false);
			}
		});
		
	}
	
	
	public int getIntegerValue() {
		return Integer.parseInt(this.getValue());
	}
	
	
	private void parseInt(boolean setDefaultValueOnEmpty) {
		String retez = this.getValue();
		String cislo = "";
		
		for (int i=0; i<retez.length(); i++) {
			if (cislo.isEmpty() && ( retez.charAt(i) == '-') ) {
				cislo += retez.charAt(i);
			}
			
			if (Character.isDigit(retez.charAt(i))) {
				cislo += retez.charAt(i);
			}
		}
		
		if (setDefaultValueOnEmpty && cislo.isEmpty()) {
			this.setValue(""+this.defaultValue);
		} else {
			this.setValue(cislo);
		}
	}
}
